package cn.smile.config.shiro.config;

import cn.smile.config.shiro.CasPathConfig;
import cn.smile.config.shiro.filter.MyCasFilter;
import cn.smile.config.shiro.filter.MyCasLogoutFilter;
import cn.smile.config.shiro.realm.MyCasRealm;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: MaoSuyu
 * @User：John
 * @Date: 2019/7/2
 * @Time: 15:16
 * @Description: No Description
 */
@Configuration
public class ShiroConfiguration {


    /**
     * 定义安全管理器securityManager,注入自定义的realm
     *
     * @return
     */
    @Bean
    public SecurityManager securityManager() {
        //这个DefaultWebSecurityManager构造函数,会对Subject，realm等进行基本的参数注入
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        //往SecurityManager中注入Realm，代替原本的默认配置
        manager.setRealm(new MyCasRealm());
        return manager;
    }

    /**
     * shiro的filter工厂，用于创建filter
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired SecurityManager manager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //绑定安全管理器
        bean.setSecurityManager(manager);
        //登录地址
        bean.setLoginUrl(CasPathConfig.LOGIN_URL);
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        //添加定义的filter
        Map<String, Filter> filters = new LinkedHashMap<>(3);
        filters.put("casFilter", new MyCasFilter());
        filters.put("logout", new MyCasLogoutFilter());
        bean.setFilters(filters);

        // 添加拦截规则
        filterChainDefinitionMap.put("/shiro-cas", "casFilter");// shiro集成cas后，首先添加该规则
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/index", "authc");
        filterChainDefinitionMap.put("/liusiqing", "authc");
        filterChainDefinitionMap.put("/sayHi", "authc");
        filterChainDefinitionMap.put("/**", "anon");
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return bean;
    }

}
